﻿package net.wangit.dev.unit;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class JRUI implements UnitInterceptor {

	public static final String KEY = "net.wangit.dev.unit.JRUI.uid";
	private static final String SQL_UNIT = "select * from UNIT where uid=?";

	public JRUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String unitShowMode = unit.getShowMode();
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			unit.getElement("gid").setDefaultValue(groupId);
		} else if (unit.getData() == null) {
			String unitId = copy ? source : getUnitId(ac);
			DB db = DBHelper.getDomainDB(domain);
			MapList data = db.query(JRUI.SQL_UNIT, unitId, 2);
			unit.setData(data);
			if (copy) {
				data.put(0, "uid", "");
				data.put(0, "l", "0");
				data.put(0, "y", "0");
			}
		}
		MapList data = unit.getData();
		if (data != null) {
			data.put(0, "domain", domain);
		} else {
			data = new MapList();
			data.put(0, "domain", domain);
			unit.setData(data);
		}
		LockUtil.setElements(ac, unit, new Object[][] { new Object[] { unit,
				"save" } });
		return unit.write(ac);
	}

	public static String getUnitId(ActionContext ac) {
		return ActionContextHelper
				.getRequest2Session(ac, "uid", JRUI.KEY, null);
	}
}
